Page({
  data: {
    cartItems: [
      { id: 1, title: '商品1', title2: '副标题1', number: 1, price: 100, spec: '规格1', image: '/image/01.jpg', checked: false },
      { id: 2, title: '商品2', title2: '副标题2', number: 1, price: 200, spec: '规格2', image: '/image/02.jpg', checked: false }
    ],
    total: 0,
    userInfo: {},
    isAllChecked: false
  },

  onLoad() {
    const userInfo = wx.getStorageSync('userInfo') || {};
    this.setData({ userInfo });
    const cartItems = wx.getStorageSync('cartItems') || [];
    // 强制将所有商品的 checked 状态设为 false
    const newCartItems = cartItems.map(item => ({ ...item, checked: false }));
    this.setData({ cartItems: newCartItems });
    this.calculateTotal();
    this.updateAllCheckStatus();
  },

  onShow() {
    const userInfo = wx.getStorageSync('userInfo') || {};
    this.setData({ userInfo });
    const cartItems = wx.getStorageSync('cartItems') || [];
    // 强制将所有商品的 checked 状态设为 false
    const newCartItems = cartItems.map(item => ({ ...item, checked: false }));
    this.setData({ cartItems: newCartItems });
    this.calculateTotal();
    this.updateAllCheckStatus();
  },

  goToLogin() {
    wx.navigateTo({
      url: '/pages/login/login'
    });
  },

  goToHome() {
    wx.switchTab({
      url: '/pages/index/index'
    });
  },

  // 勾选单个商品
  onCheckItem(e) {
    const index = e.currentTarget.dataset.index;
    const cartItems = [...this.data.cartItems];
    if (cartItems[index]) {
      cartItems[index].checked = !cartItems[index].checked;
      this.setData({ cartItems });
      wx.setStorageSync('cartItems', cartItems);
      this.calculateTotal();
      this.updateAllCheckStatus();
    } else {
      console.error('未找到对应的购物车商品，索引:', index);
    }
  },

  // 减少商品数量
  decreaseQuantity(e) {
    const index = e.currentTarget.dataset.index;
    const cartItems = [...this.data.cartItems];
    if (cartItems[index] && cartItems[index].number > 1) {
      cartItems[index].number--;
      this.setData({ cartItems });
      wx.setStorageSync('cartItems', cartItems);
      this.calculateTotal();
    }
  },

  // 增加商品数量
  increaseQuantity(e) {
    const index = e.currentTarget.dataset.index;
    const cartItems = [...this.data.cartItems];
    if (cartItems[index]) {
      cartItems[index].number++;
      this.setData({ cartItems });
      wx.setStorageSync('cartItems', cartItems);
      this.calculateTotal();
    }
  },

  // 删除选中商品
  deleteSelectedItems() { 
    let cartItems = [...this.data.cartItems]; 
    cartItems = cartItems.filter(item => !item.checked); 
    this.setData({ cartItems }); 
    wx.setStorageSync('cartItems', cartItems); 
    this.calculateTotal(); 
    this.updateAllCheckStatus(); 
  }, 
  // 计算选中商品的总价
  calculateTotal() {
    let total = 0;
    this.data.cartItems.forEach(item => {
      if (item.checked) {
        total += item.number * item.price;
      }
    });
    // 保留两位小数
    total = parseFloat(total.toFixed(2));
    console.log('计算得到的总价:', total);
    console.log('当前购物车数据:', this.data.cartItems);
    this.setData({ total });
  },

  // 全选/全不选功能
  toggleAllCheck() {
    const isAllChecked = !this.data.isAllChecked;
    const cartItems = this.data.cartItems.map(item => ({
      ...item,
      checked: isAllChecked
    }));
    this.setData({ cartItems, isAllChecked });
    wx.setStorageSync('cartItems', cartItems);
    this.calculateTotal();
  },

  // 更新全选按钮状态
  updateAllCheckStatus() {
    const allChecked = this.data.cartItems.every(item => item.checked);
    this.setData({ isAllChecked: allChecked });
  },

  // 提交订单
  onCheckout() {
    const selectedItems = this.data.cartItems.filter(item => item.checked);
    if (selectedItems.length === 0) {
      wx.showToast({
        title: '请选择要购买的商品',
        icon: 'none'
      });
      return;
    }
    // 计算选中商品总价
    let totalPrice = 0;
    selectedItems.forEach(item => {
      totalPrice += item.number * item.price;
    });
    totalPrice = parseFloat(totalPrice.toFixed(2));
    
    // 跳转到确认订单页并传递订单信息
    wx.navigateTo({
      url: `/pages/confirmOrder/confirmOrder?orderInfo=${encodeURIComponent(JSON.stringify({
        goodsList: selectedItems,
        totalPrice: totalPrice
      }))}`
    });

    // 移除已选中的商品
    const newCartItems = this.data.cartItems.filter(item => !item.checked);
    this.setData({ cartItems: newCartItems });
    wx.setStorageSync('cartItems', newCartItems);
    this.calculateTotal();
    this.updateAllCheckStatus();
  }
});